package org.qydjk.console.controller.common;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.shiro.captcha.QYCaptcha;
import org.qydjk.common.util.StringUtil;
import org.qydjk.console.websocket.TextMessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;

@Controller
@RequestMapping("/common")
public class CommonController extends BaseController{
    @Autowired
    private QYCaptcha qyCaptcha;

    /**
     * 进入登陆页面
     * @return
     */
    @RequestMapping("/login.do")
    public String login(){
        return "login";
    }

    /**
     * 进入登陆页面
     * @return
     */
    @RequestMapping("/doLogin.do")
    @ResponseBody
    public Object doLogin( String username, String password, String captcha, @RequestParam(value = "rememberMe", defaultValue = "0")  Integer rememberMe){
        logger.info("POST请求登录");
        // 改为全部抛出异常，避免ajax csrf token被刷新
        if (StringUtil.isEmptyOrNull(username)) {
            return renderError("用户名不能为空");
        }
        if (StringUtil.isEmptyOrNull(password)) {
            return renderError("密码不能为空");
        }
        if (StringUtil.isEmptyOrNull(captcha)) {
            return renderError("验证码不能为空");
        }
        if (!qyCaptcha.validate(request, response, captcha)) {
            return renderError("验证码错误");
        }
        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 设置记住密码
        token.setRememberMe(1 == rememberMe);
        try {
            user.login(token);
            return renderSuccess();
        } catch (UnknownAccountException e) {
            return renderError("账号不存在！");
        } catch (DisabledAccountException e) {
            return renderError("账号未启用！");
        } catch (IncorrectCredentialsException e) {
            return renderError("密码错误！");
        } catch (Throwable e) {
            return renderError(e.getMessage());
        }
    }

    /**
     * 退出
     * @return {Result}
     */
    @RequestMapping("/logout.do")
    @ResponseBody
    public Object logout() {
        logger.info("登出");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return renderSuccess();
    }

    /**
     * 图形验证码
     */
    @RequestMapping("/captcha.do")
    public void captcha() {
        qyCaptcha.generate(request, response);
    }

    @GetMapping("icons.do")
    public String icons() {
        return "icons";
    }

    /**
     * 未授权
     * @return {String}
     */
    @RequestMapping("/unauth.do")
    public String unauth() {
        if (SecurityUtils.getSubject().isAuthenticated() == false) {
            return "redirect:/login";
        }
        return "unauth";
    }

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping("/index.do")
    public String index() {
        return "index";
    }

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping("/test.do")
    public void test() throws Exception {
        //对
        //List<SUserRole> userRoleList1 = baseService.findByHql("from SUserRole where userId = ?", 1);
        //错
        //List<SUserRole> userRoleList3 = baseService.findByHql("select t.id,t.userId,t.roleId from SUserRole t where t.userId = ?", 1);

        //对
        //List<Map<String, Object>> aa = baseService.findMapBySQL("select t.id,t.user_id,t.role_id from s_user_role t where t.user_id = ?", 1);
        //对
        //List<Integer> bb = baseService.findByHql("select t.roleId from SUserRole t where t.userId = ?", 1);
    }

    @RequestMapping("/send.do")
    @ResponseBody
    public String send(String un,String msg) {
        TextMessage message = new TextMessage(msg);
        textMessageHandler().sendMessageToUser(un, message);
        return "true";
    }

    @Bean
    public TextMessageHandler textMessageHandler() {
        return new TextMessageHandler();
    }

}
